package com.example.captchademo.controller;

import cn.hutool.captcha.CaptchaUtil;
import cn.hutool.captcha.LineCaptcha;
import com.example.captchademo.model.CaptchaProperties;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.servlet.http.HttpSession;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.IOException;
import java.util.Date;

@RestController
@RequestMapping("/captcha")
public class CaptchaController {

    // 从日志工厂LoggerFactory中获得对象logger,利用该对象去打印日志
    private static Logger logger=LoggerFactory.getLogger(CaptchaController.class);

    // 将CaptchaProperties 中的对象注入进来
    @Autowired
    private CaptchaProperties cp;

    private static long VALID_TIME_OUT=60*1000;// 过期时间为1分钟(60s*1000ms)


    @GetMapping("/getCaptcha")
    public void getCaptcha(HttpSession session, HttpServletResponse response){   // 向浏览器输出一个验证码图片
        // 生成验证码图片
        LineCaptcha lineCaptcha = CaptchaUtil.createLineCaptcha(cp.getWidth(), cp.getHeight());
        String code =lineCaptcha.getCode();
        // 打印出验证码看一下
        System.out.println("System生成验证码: "+code);

        logger.info("Logger生成验证码: "+code);

        // 将验证码存储到session
        session.setAttribute(cp.getSession().getKey(),code);
        // 存储当前时间
        session.setAttribute(cp.getSession().getDate(),new Date());
        try {
            // 把验证码写到response,带到浏览器中
            lineCaptcha.write(response.getOutputStream());
            response.setContentType("image/jpeg");// 设置图片格式
            response.setCharacterEncoding("utf-8");// 指定response的编码方式
            response.setHeader("Pragma","No-cache");// 防止缓存
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @RequestMapping("/check")
    public Boolean check(String captcha,HttpSession session) {
        System.out.println("用户输入验证码: "+captcha);
        if(!StringUtils.hasLength(captcha)) {
            return false;// session中没有验证码信息
        }
        // 校验
        String code=(String)session.getAttribute(cp.getSession().getKey());
        Date date = (Date)session.getAttribute(cp.getSession().getDate());
        // 当时间对象不存在或者过期,返回false
        if(date==null || (System.currentTimeMillis()-date.getTime())>VALID_TIME_OUT) {
            return false;
        }
        return captcha.equalsIgnoreCase(code);// 不区分大小写地校验验证码是否匹配
    }
}
